package com.zhang.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.zhang.entity.response.ResponseResult;
import com.zhang.entity.response.ResultCode;
import com.zhang.entity.vo.LoginBody;
import com.zhang.entity.vo.RegisterBody;
import com.zhang.entity.vo.ResetPasswordBody;
import com.zhang.entity.vo.VerificationCodeBody;
import com.zhang.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * Created with IntelliJ IDEA.
 * User: 张
 * Date: 2024-10-28
 * Time: 10:23
 * Description:
 */
@RestController
@RequestMapping("/basic")
public class UserController {

    @Autowired
    private UserInfoService userService;

    /**
     * 处理用户登录请求
     *
     * 该方法接收一个LoginBody对象作为参数，其中包含了用户登录所需的信息，如用户名和密码
     * 使用@PostMapping注解表明该方法仅响应POST请求
     *
     * @param form 包含用户登录信息的LoginBody对象，通过请求体接收
     * @return ResponseResult<String> 登录操作的结果封装在ResponseResult对象中
     *         如果登录成功，返回成功信息；否则，返回错误信息
     */
    @PostMapping("/doLogin")
    public ResponseResult<Object> doLogin(@RequestBody LoginBody form) {
        return userService.doLogin(form) ? ResponseResult.success(StpUtil.getTokenInfo().getTokenValue()) : ResponseResult.error("登录失败,账号或密码错误");
    }

    @PostMapping("/register")
    public ResponseResult<String> register(@RequestBody RegisterBody registerBody) {
        userService.register(registerBody);
        return ResponseResult.success();
    }

    @RequestMapping("/doLogout")
    public ResponseResult<String> doLogin() {
        StpUtil.logout(StpUtil.getLoginIdAsInt());
        return ResponseResult.success("退出成功");
    }

    @GetMapping("/getVerificationCode")
    public ResponseResult<String> getVerificationCode(@RequestBody VerificationCodeBody code) {
        return userService.sendVerificationCode(code.getPhone());
    }

    @PostMapping("/resetPassword")
    public ResponseResult<String> resetPassword(@RequestBody ResetPasswordBody resetPasswordBody){
        ResultCode resultCode = userService.resetPassword(resetPasswordBody);
        if (resultCode.equals(ResultCode.SUCCESS)) return ResponseResult.success();
        else return ResponseResult.error(resultCode.getMsg());
    }
    @SaIgnore
    @RequestMapping("/hello")
    public ResponseResult<String> hello(){
        return ResponseResult.success("hello world ,This is gateway-service");
    }

}
